package cn.y.operation.framework.utils.system;

import cn.y.operation.application.core.entity.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.session.mgt.WebSessionKey;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class UserUtils {

    /**
     * 获取当前登录用户
     */
    public static SysUser getShiroUser() {
        Subject subject = SecurityUtils.getSubject();
        return (SysUser) subject.getPrincipal();
    }

    /**
     * 获取当前登录用户 userName
     */
    public static String getUserName() {
        return getShiroUser().getUserName();
    }

    /**
     * 获取当前登录用户session
     */
    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    /**
     * 获取当前登录用户session id
     */
    public static String getSessionId() {
        return getSession().getId().toString();
    }

    /**
     * 验证是否登陆
     */
    public static boolean isAuthenticated() {
        return SecurityUtils.getSubject().isAuthenticated();
    }

    /*public static boolean isAuthenticated(HttpServletRequest request, HttpServletResponse response) {
        boolean result = false;
        String sessionID = getSessionId();
        SessionKey key = new WebSessionKey(sessionID, request, response);
        try {
            Session se = SecurityUtils.getSecurityManager().getSession(key);
            Object obj = se.getAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY);
            if (obj != null) {
                result = (Boolean) obj;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Session se = null;
            Object obj = null;
        }
        return result;
    }*/

}
